package pwd.allen.readListener;

import cn.hutool.json.JSON;
import cn.hutool.json.JSONUtil;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.exception.ExcelDataConvertException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.function.BiConsumer;

/**
 * 自定义数据监听器：分批读取数据
 *
 * @author pwdan
 * @create 2020-05-19 22:57
 **/
public class ListDataListener<T> extends AnalysisEventListener<T> {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    private int batch_count = 1000;
    private List<T> list = null;
    private BiConsumer<List<T>, AnalysisContext> consumer;

    public ListDataListener(int batch_count, BiConsumer<List<T>, AnalysisContext> consumer) {
        this.batch_count = batch_count;
        this.list = new ArrayList<>(batch_count);
        this.consumer = consumer;
    }

    /**
     * 这个每一条数据解析都会来调用
     * @param data
     * @param context
     */
    @Override
    public void invoke(T data, AnalysisContext context) {
        list.add(data);
        // 达到BATCH_COUNT了，需要去存储一次数据库，防止数据几万条数据在内存，容易OOM
        if (list.size() >= batch_count) {
            consumer.accept(list, context);
            // 完成后清理 list
            list.clear();
        }
    }

    /**
     * 所有数据解析完成后回调，hasNext方法如果中途返回false则不会回调doAfterAllAnalysed方法
     * @param context
     */
    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        if (list.size() > 0) {
            consumer.accept(list, context);
        }
    }

    /**
     * 每读取一行数据回调一次，返回false则不处理当前行数据以及后面的数据，而且不会再回调doAfterAllAnalysed方法
     * @param context
     * @return
     */
    @Override
    public boolean hasNext(AnalysisContext context) {
        return super.hasNext(context);
    }

    /**
     * 解析行头时回调
     * @param headMap
     * @param context
     */
    @Override
    public void invokeHeadMap(Map<Integer, String> headMap, AnalysisContext context) {
        logger.info("解析到一条头数据:{}", JSONUtil.toJsonPrettyStr(headMap));
    }

    /**
     * 转换或者获取发生异常时会调用本接口。抛出异常则停止读取。如果这里不抛出异常则 继续读取下一行。
     * @param exception
     * @param context
     * @throws Exception
     */
    @Override
    public void onException(Exception exception, AnalysisContext context) throws Exception {
        logger.error("解析失败，但是继续解析下一行:{}", exception.getMessage());
        if (exception instanceof ExcelDataConvertException) {
            ExcelDataConvertException excelDataConvertException = (ExcelDataConvertException)exception;
            logger.error("第{}行，第{}列解析异常，数据为:{}", excelDataConvertException.getRowIndex(),
                    excelDataConvertException.getColumnIndex(), excelDataConvertException.getCellData());
        }
        super.onException(exception, context);
    }
}
